package cn.zwx.business.order.remote;

import cn.zwx.business.order.api.req.RpcRequest;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 *  集中处理invoker逻辑
 *  @author zhangwenxue
 */
public class Mediator {

    public static Map<String,BeanMethod> mapCache = new ConcurrentHashMap<>(8);

    private volatile static  Mediator instance ;

    public static Mediator getInstance(){
        if (null == instance){
            synchronized (Mediator.class){
             if (null == instance){
                instance = new Mediator();
               }
            }
        }
        return instance;
    }


    /**
     * 处理调用逻辑
     * @param request 请求参数
     * @return 返回对象
     */
    public Object process(RpcRequest request) throws InvocationTargetException, IllegalAccessException {
        String key =  request.getClassName()+"."+ request.getMethodName()+"."+ Arrays.toString(request.getType());
        BeanMethod beanMethod = mapCache.get(key);
        if (Objects.isNull(beanMethod)){
            return null;
        }
        Object service = beanMethod.getBean();
        Method method = beanMethod.getMethod();
        return method.invoke(service, request.getArgs());
    }


}
